﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using Newtonsoft.Json;
using System.Web.Services.Protocols;
using System.Web.Security;

namespace NCAB.WF.services
{
    /// <summary>
    /// Summary description for WS_Usuarios
    /// </summary>
    [WebService(Namespace = "http://netcorp-panama.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WS_User : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetUsuario_ByUserName(string UserName, string WSUser, string WSPass)
        {
            try
            {
                aspnetdb_ncabDataContext ncab = new aspnetdb_ncabDataContext();

                if (ncab.SP_S_aspnet_WebService_Verify(WSUser, WSPass).Count() > 0)
                {
                    List<SP_S_aspnet_UserExtraInfoResult> usuario = ncab.SP_S_aspnet_UserExtraInfo(UserName).ToList();

                    if (usuario.Count() > 0)
                        return JsonConvert.SerializeObject(usuario.First());
                    else
                        return null;
                }

                return null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string UpdatePassword(string OldPassword, string NewPassword)
        {
            try
            {
                MembershipUser u = Membership.GetUser(User.Identity.Name);

                if (u.ChangePassword(OldPassword, NewPassword))
                {
                    return "true";
                }

                else
                {
                    return "false";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public bool UpdateUser(aspnet_UserExtraInfo user, string WSUser, string WSPass)
        {
            try
            {
                aspnetdb_ncabDataContext ncab = new aspnetdb_ncabDataContext();

                if (ncab.SP_S_aspnet_WebService_Verify(WSUser, WSPass).Count() > 0)
                {
                    aspnet_UserExtraInfo user_selected = (from userextra in ncab.aspnet_UserExtraInfos
                                                          where userextra.NombreUsuario == user.NombreUsuario
                                                          select userextra).First();

                    user_selected.Nombres = user.Nombres;
                    user_selected.Apellidos = user.Apellidos;
                    user_selected.Identificacion = user.Identificacion;
                    user_selected.TMovil = user.TMovil;
                    user_selected.TOficina = user.TOficina;
                    user_selected.Direccion = user.Direccion;
                    user_selected.AboutMe = user.AboutMe;

                    ncab.SubmitChanges();

                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string CreateUser(aspnet_UserExtraInfo user)
        {
            try
            {
                //CREACIÓN DEL USUARIO DEL LADO DE ASPNETDB
                MembershipCreateStatus estado;
                MembershipUser nuevo_usuario = Membership.CreateUser(user.NombreUsuario, "123.abc.", user.Email, "¿Cómo me llamo?", "Carlos Vertiz", true, out estado);

                if (nuevo_usuario == null)
                {
                    switch (estado)
                    {
                        case MembershipCreateStatus.DuplicateUserName:
                            return "Username already exists. Please enter a different user name.";

                        case MembershipCreateStatus.DuplicateEmail:
                            return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                        case MembershipCreateStatus.InvalidPassword:
                            return "The password provided is invalid. Please enter a valid password value.";

                        case MembershipCreateStatus.InvalidEmail:
                            return "The e-mail address provided is invalid. Please check the value and try again.";

                        case MembershipCreateStatus.InvalidAnswer:
                            return "The password retrieval answer provided is invalid. Please check the value and try again.";

                        case MembershipCreateStatus.InvalidQuestion:
                            return "The password retrieval question provided is invalid. Please check the value and try again.";

                        case MembershipCreateStatus.InvalidUserName:
                            return "The user name provided is invalid. Please check the value and try again.";

                        case MembershipCreateStatus.ProviderError:
                            return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                        case MembershipCreateStatus.UserRejected:
                            return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                        default:
                            return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
                    }
                }
                else
                {
                    //NO EXISTE ERROR AL REGISTRAR EL USUARIO EN ASPNETDB, SE INSERTAN LOS VALORES EN EL EXTRAINFO.
                    aspnetdb_ncabDataContext ncab = new aspnetdb_ncabDataContext();
                    user.UserId = (Guid)nuevo_usuario.ProviderUserKey;

                    ncab.aspnet_UserExtraInfos.InsertOnSubmit(user);
                    ncab.SubmitChanges();
                    return "Se creó correctamente el usuario.";
                }                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
